package xyz.liuz.edb.heart.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;

public class HeartClinet {

    private static HeartClinet instance = new HeartClinet();
    public static HeartClinet getInstance() {
        return instance;
    }
    public static void HeartClinet(){}



    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(new HeartClientChannelInitializer());

        ChannelFuture f = b.connect("127.0.0.1", 8889);
        //断线重连
        f.addListener(
                new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()){
                            final EventLoop loop = future.channel().eventLoop();
                            loop.schedule(
                                    new Runnable() {
                                        @Override
                                        public void run() {
                                            System.out.println("无法连接到服务器，正在尝试重连");
                                            start();
                                        }
                                    },1L, TimeUnit.SECONDS
                            );
                        }else{
                            System.out.println("连接服务端:"+future.channel().remoteAddress()+"成功!");
                        }
                    }
                }
        );


//        try {
//            f.channel().closeFuture().sync();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }finally {
//            group.shutdownGracefully();
//        }
    }

    public static void main(String[] args){
        HeartClinet.getInstance().start();

    }
}
